package com.iakuil.app.common.ws.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.iakuil.app.common.core.constant.RedisConstant;
import com.iakuil.app.common.core.util.JsonUtils;
import com.iakuil.app.common.redis.base.RedisTopicListener;
import com.iakuil.app.common.ws.dto.SysMsg;
import com.iakuil.app.common.ws.utils.WsSessionUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

/**
 * 单播消息监听器
 *
 * <p>基于Redis Pub/Sub，订阅单播Channel，发送消息给指定用户。
 *
 * @author Kai
 */
@Component
public class UnicastRedisMessageListener implements RedisTopicListener {

    private final RedisTemplate<String, Object> redisTemplate;

    public UnicastRedisMessageListener(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void onMessage(Message message, byte[] bytes) {
        byte[] messageBody = message.getBody();
        SysMsg msg = Convert.convert(new TypeReference<>() {
        }, redisTemplate.getValueSerializer().deserialize(messageBody));

        WsSessionUtils.sendMessage(msg.getTo(), JsonUtils.bean2Json(msg));
    }

    @Override
    public Topic getTopic() {
        return new ChannelTopic(RedisConstant.WS_UNICAST_CHANNEL);
    }
}
